package com.jiaquyun.jcps.ui.main

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.LogUtils
import com.jiaquyun.jcps.R
import com.jiaquyun.jcps.base.ViewModeActivity
import com.jiaquyun.jcps.mode.vm.MainViewModel
import com.jiaquyun.jcps.popup.ConfirmCancelPopup
import com.jiaquyun.jcps.ui.mine.MineActivity
import com.jiaquyun.jcps.utils.AMapLocationUtils
import com.jiaquyun.jcps.utils.HttpWebSocketUtils
import com.lemlin.network.HttpServiceStatus
import com.yxing.ScanCodeActivity
import com.yxing.ScanCodeConfig
import com.yxing.def.ScanStyle
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.StringBuilder


class MainActivity : ViewModeActivity<MainViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, MainActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val confirmCancelPopup: ConfirmCancelPopup by lazy {
        ConfirmCancelPopup(
            context = this,
            onConfirm = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()
                if (action == null)
                    return@ConfirmCancelPopup
                when (action) {
                    ConfirmCancelPopup.Action.CONFIRM_TASK -> {
                        vpMainBody.currentItem = 1
                        rbMainPickup.isChecked = true
                    }
                    ConfirmCancelPopup.Action.CONFIRM_PICKUP -> {

                    }
                    ConfirmCancelPopup.Action.CONFIRM_CALL -> {
                        val intent = Intent(Intent.ACTION_DIAL)
                        intent.data = Uri.parse("tel:${any.toString()}")
                        startActivity(intent)
                    }
                }
            },
            onCancel = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()
            })
    }

    override fun viewModel(): MainViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = false, view = flMainBar)
    }

    override fun initView() {

        val fragments: MutableList<Fragment> = mutableListOf(
            MainTaskFragment.newInstance(),
            MainPickupFragment.newInstance(),
            MainGiveFragment.newInstance()
        )

        vpMainBody.apply {
            offscreenPageLimit = 3
        }.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment =
                fragments[position]

            override fun getCount(): Int = fragments.size

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
        }

        vpMainBody.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) = Unit

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) = Unit

            override fun onPageSelected(position: Int) {
                when (position) {
                    1 -> rbMainPickup.isChecked = true
                    2 -> rbMainGive.isChecked = true
                    else -> rbMainTask.isChecked = true
                }
            }
        })

        rbMainTask.setOnClickListener {
            vpMainBody.currentItem = 0
        }
        rbMainPickup.setOnClickListener {
            vpMainBody.currentItem = 1
        }
        rbMainGive.setOnClickListener {
            vpMainBody.currentItem = 2
        }

        //我的页面
        ivMainMine.setOnClickListener {
            MineActivity.open(activity = this)
        }
        //更多页面
        ivMainMore.setOnClickListener {

        }
    }

    override fun initData() {
        viewModel.startLocation()
        viewModel.startOrderRefresh()
        viewModel.orderListTab()
    }

    override fun initViewMode() {

        AMapLocationUtils.instance()?.locationDataLiveData?.observe(this, Observer { map ->
            viewModel.sendLocation(map)
        })

        viewModel.orderTabLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                response.httpData?.data?.let {
                    rbMainPickup.text =
                        StringBuilder().append("待取货(").append(it.to_be_picked_up).append(")")
                    rbMainGive.text =
                        StringBuilder().append("待送达(").append(it.to_be_served).append(")")
                }
            }
        })

        viewModel.baseReceivingLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                confirmCancelPopup.setMessage("接单成功， 请到待取货界面，查看订单详情!")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_TASK)
                    .setGoneCancel(true)
                    .showPopupWindow()
                viewModel.orderListTask()
                viewModel.orderListTab()
                viewModel.orderListPickUp()
            }
        })

        viewModel.baseWithdrawalLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                confirmCancelPopup.setMessage("取货完成， 是否立即导航送货？")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_PICKUP)
                    .showPopupWindow()
                viewModel.orderListTab()
                viewModel.orderListPickUp()
                viewModel.orderListGive()
            }
        })

        viewModel.baseServiceLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                confirmCancelPopup.setMessage("辛苦了，已经成功送达")
                    .setAction(null)
                    .showPopupWindow()
                viewModel.orderListTab()
                viewModel.orderListGive()
            }
        })

        viewModel.baseCallPhoneLiveData.observe(this, Observer { phone ->
            phone?.let {
                confirmCancelPopup.setMessage("联系电话：${phone}")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_CALL)
                    .setAny(it)
                    .showPopupWindow()
            }
        })
    }

    override fun onRestart() {
        super.onRestart()
        viewModel.orderListTab()
        viewModel.orderListGive()
    }

}